package com.ruoyi.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;


/**
 * Title: Kernel Library
 * <p>
 * Description: 有关Web开发中使用的工具类
 * <p>
 * Copyright: Copyright (c) 2010 - 2011
 * <p>
 * @author Charles (Li Hui)
 * @version 1.0.2
 */
public class WebUtil {

	/**
	 * 判断是否url地址
	 * 
	 * @author Charles (Li Hui)
	 * @date 2011-10-19 上午11:00:04
	 * @param url
	 *            地址
	 * @return true/false
	 */
	public static boolean isUrl(final String url) {
		boolean isOk = false;
		if (StringUtils.isNotEmpty(url)) {
			final String pattern = "(http://|https://){1}[\\w\\.\\-/:]+";
			final Matcher matcher = Pattern.compile(pattern).matcher(url);
			if (matcher.find()) {
				isOk = true;
			}
		}
		return isOk;
	}

	/**
	 * 判断是否是IP地址
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isIPAdress(final String str) {
		final String  pattern = "^((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]|[*])\\.){3}(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]|[*])$";
		return Pattern.compile(pattern).matcher(str).matches();
	}

	/**
	 * 获取用户真实Ip
	 * 
	 * @author Charles (Li Hui)
	 * @date 2011-8-29 上午11:32:12
	 * @param request
	 *            HttpServletRequest
	 * @return Ip地址
	 */
	public static String getIpAddr(final HttpServletRequest request) {
		String ip = null;
		if (request != null) {
			ip = request.getHeader("x-forwarded-for");
			if ((ip == null) || (ip.length() == 0) || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
			}
			if ((ip == null) || (ip.length() == 0) || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
			}
			if ((ip == null) || (ip.length() == 0) || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
			}
		}
		return ip;
	}


	/**
	 * 获取当前操作系统名称. return 操作系统名称 例如:windows xp,linux 等.
	 */
	public static String getOSName() {
		return System.getProperty("os.name").toLowerCase();
	}

	/**
	 * 批量执行DOC命令
	 * 
	 * @author Charles (Li Hui)
	 * @param cmd
	 *            命令集合
	 * @return 执行后的返回结果
	 */
	public static String callCmd(final String[] cmd) {
		String result = "";
		String line = "";
		try {
			final Process proc = Runtime.getRuntime().exec(cmd);
			final InputStreamReader is = new InputStreamReader(proc.getInputStream());
			final BufferedReader br = new BufferedReader(is);
			while ((line = br.readLine()) != null) {
				result += line;
			}
		} catch (final Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 通过IP获取客户端机器的MAC地址
	 * 
	 * @author Charles (Li Hui)
	 * @param ip
	 *            客户端IP地址
	 * @return MAC地址
	 */
	public static String getMACAddress(final String ip) {
		// 本机就不需要获取MAC地址了
		if (StringUtils.isNotEmpty(ip) && !"127.0.0.1".equals(ip)
				&& !"localhost".equalsIgnoreCase(ip)) {
			final String os = WebUtil.getOSName();
			// System.out.println(os);

			if (os.startsWith("windows")) {
				// 服务器是windows操作系统
				return WebUtil.getWindowsMac(ip);
			} else {
				// 服务器是非windows操作系统
				return WebUtil.getLinuxMac(ip);
			}
		} else {
			return "";
		}
	}

	/**
	 * 在windows服务器中获取mac地址
	 * 
	 * @author Charles (Li Hui)
	 * @param ip
	 *            客户端IP
	 * @return MAC地址
	 */
	private static String getWindowsMac(final String ip) {
		String str = "", strMAC = "", macAddress = "";
		try {
			final Process pp = Runtime.getRuntime().exec("nbtstat -a " + ip);
			final InputStreamReader ir = new InputStreamReader(pp.getInputStream());
			final LineNumberReader input = new LineNumberReader(ir);
			for (int i = 1; i < 100; i++) {
				str = input.readLine();
				if (str != null) {
					if (str.indexOf("MAC Address") > 1) {
						strMAC = str.substring(str.indexOf("MAC Address") + 14, str.length());
						break;
					}
				}
			}
		} catch (final IOException ex) {
			return "Can't Get MAC Address!";
		}
		if (strMAC.length() < 17) {
			return "Error!";
		}

		macAddress = strMAC.substring(0, 2) + ":" + strMAC.substring(3, 5) + ":"
				+ strMAC.substring(6, 8) + ":" + strMAC.substring(9, 11) + ":"
				+ strMAC.substring(12, 14) + ":" + strMAC.substring(15, 17);
		return macAddress;

	}

	/**
	 * 在linux服务器中获取mac地址
	 * 
	 * @author Charles (Li Hui)
	 * @param ip
	 *            客户端IP
	 * @return MAC地址
	 */
	private static String getLinuxMac(final String ip) {
		final String[] cmd = new String[] { "/bin/sh", "-c", "ping " + ip + " -c 2 && arp -a" };
		String result = WebUtil.callCmd(cmd);
		final Pattern pattern = Pattern.compile("((([0-9,A-F,a-f]{1,2}:){1,5})[0-9,A-F,a-f]{1,2})");
		final Matcher matcher = pattern.matcher(result);
		while (matcher.find()) {
			result = matcher.group(1);
			if (result.indexOf(ip) <= result.lastIndexOf(matcher.group(1))) {
				break;
			}
		}
		return result;
	}

	/**
	 * 获取URL的模型
	 * <p>
	 * 例如：http://localhost:8080/disk
	 * <p>
	 * 输出：localhost:8080
	 * 
	 * @param uri
	 *            URL地址
	 * @return 模型
	 */
	public static String getModule(final String uri) {
		if (uri == null) {
			return "";
		}
		final String[] uriArr = uri.split("/");
		if (uriArr != null && uriArr.length > 2) {
			return uriArr[2];
		} else {
			return "";
		}
	}

	/**
	 * 获取URL的HOST
	 * <p>
	 * 例如：http://localhost:8080/disk
	 * <p>
	 * 输出：localhost
	 * 
	 * @param url
	 *            URL地址
	 * @return 模型
	 */
	public static String getHost(final String url) {
		if (url == null) {
			return "";
		}
		if (url.indexOf("http://") == 0) {
			return StringUtils.substringBetween(url, "http://", ":");
		} else if (url.indexOf("https://") == 0) {
			return StringUtils.substringBetween(url, "https://", ":");
		}
		return StringUtils.substringBefore(url, ":");
	}

	/**
	 * 获取网站URL地址
	 * <p>
	 * 例如：http://localhost:8080/test
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return 地址
	 */
	public static String getWebUrl(final HttpServletRequest request) {
		if (request == null) {
			return "";
		}
		return request.getScheme() + "://" + request.getServerName() + ":"
				+ request.getServerPort() + request.getContextPath() + "/";
	}

	/**
	 * 获取某一个url的ip
	 * <p>
	 * 例如：http://platform.24mim.cn:80
	 * <p>
	 * 返回：192.168.100.122
	 * <p>
	 * 例如：platform.24mim.cn:80
	 * <p>
	 * 返回：192.168.100.122
	 * <p>
	 * 例如：platform.24mim.cn
	 * <p>
	 * 返回：192.168.100.122
	 * <p>
	 * 例如：192.168.100.122
	 * <p>
	 * 返回：192.168.100.122
	 * 
	 * @param url
	 *            URL地址
	 * @return IP
	 */
	public static String getIpFromUrl(final String url) {
		if (StringUtils.isEmpty(url)) {
			return "";
		}
		try {
			final InetAddress iAddress = InetAddress.getByName(WebUtil.getHost(url));
			return iAddress.getHostAddress();
		} catch (final UnknownHostException e) {
			return "";
		}
	}

	/**
	 * 测试
	 * 
	 * @author Charles (Li Hui)
	 * @date 2012-3-21 上午9:15:01
	 * @param args
	 *            参数
	 */
	public static void main(final String[] args) {
		System.out.println(WebUtil.getModule("http://localhost:8080/disk/download.xhtml"));
		System.out.println(WebUtil.getHost("http://localhost:8080/disk/download.xhtml"));
		System.out.println(WebUtil.getIpFromUrl("http://platform.24mim.cn:80"));
		System.out.println(WebUtil.isIPAdress("10.0.2.54"));
		System.out.println(WebUtil.getMACAddress("10.0.2.54"));
	}
	
	
	/**
	 * 创建注册会员订单编号 (时间戳yy-MM-dd HH:mm:ss, 5位随机数)
	 *
	 * @return
	 */
	public static String createZCOrderNum() {
		DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
		String dateStr = format.format(new Date());
		Random rand = new Random();
		int randomNumber = rand.nextInt(99999);

		String orderNo = "ZC" + dateStr + String.valueOf(randomNumber);
		return orderNo;
	}

	/**
	 * 创建充值心币订单编号 (时间戳yy-MM-dd HH:mm:ss, 5位随机数)
	 *
	 * @return
	 */
	public static String createCZOrderNum() {
		DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
		String dateStr = format.format(new Date());
		Random rand = new Random();
		int randomNumber = rand.nextInt(99999);

		String orderNo = "CZ" + dateStr + String.valueOf(randomNumber);
		return orderNo;
	}

	/**
	 * 创建VIP注册订单编号 (时间戳yy-MM-dd HH:mm:ss, 5位随机数)
	 *
	 * @return
	 */
	public static String createVIPOrderNum() {
		DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
		String dateStr = format.format(new Date());
		Random rand = new Random();
		int randomNumber = rand.nextInt(99999);

		String orderNo = "VIP" + dateStr + String.valueOf(randomNumber);
		return orderNo;
	}
	
	/**
	 * 创建订单编号 (时间戳yy-MM-dd HH:mm:ss, 5位随机数)
	 *
	 * @return
	 */
	public static String createCashOutNum(String str) {
		DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
		String dateStr = format.format(new Date());
		Random rand = new Random();
		int randomNumber = rand.nextInt(99999);

		String orderNo = str + dateStr + String.valueOf(randomNumber);
		return orderNo;
	}
	
	/**
	 * 创建优惠券码 (时间戳yy-MM-dd HH:mm:ss, 5位随机数)
	 *
	 * @return
	 */
	public static String createCouponCode() {
		DateFormat format = new SimpleDateFormat("HHmmss");
		String dateStr = format.format(new Date());
		Random rand = new Random();
		int randomNumber = rand.nextInt(99999999);

		String orderNo = dateStr + String.valueOf(randomNumber);
		return orderNo;
	}
	
	
	/**
	 * 创建vip会员编号 (时间戳yy-MM-dd HH:mm:ss, 5位随机数)
	 *
	 * @return
	 */
	public static String createVipNum() {
		DateFormat format = new SimpleDateFormat("yyMMdd");
		String dateStr = format.format(new Date());
		Random rand = new Random();
		int randomNumber = rand.nextInt(9999);

		String orderNo = "VIP-"+dateStr + String.valueOf(randomNumber);
		return orderNo;
	}
	
	/**
	 * 创建邮件验证码(6位随机数)
	 *
	 * @return
	 */
	public static String createMailCode() {
		Random rand = new Random();
		int randomNumber = rand.nextInt(999999);
		return String.valueOf(randomNumber);
	}
	
	/**
	 * 创建im调用接口随机数(8位随机数)
	 *
	 * @return
	 */
	public static int createImRandom() {
		Random rand = new Random();
		int randomNumber = rand.nextInt(99999999);
		return randomNumber;
	}

	/**
	 * 创建精英订单编号 (时间戳yy-MM-dd HH:mm:ss, 5位随机数)
	 *
	 * @return
	 */
	public static String createJyNum() {
		DateFormat format = new SimpleDateFormat("yyMMddHHmmssSSS");
		String dateStr = format.format(new Date());
		Random rand = new Random();
		int randomNumber = rand.nextInt(99999);

		String orderNo = "JY" + dateStr + String.valueOf(randomNumber);
		return orderNo;
	}


}
